package org.zjvis.datascience.common.util;

import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.zjvis.datascience.common.constant.DatasetConstant;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description 字符串工具类
 * @date 2021-10-29
 */
public class StringUtil {


    public static boolean hasChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

    public static Object genLexicalKey(int index) {
        String colCode = "";
        char key = 'A';
        int loop = index / 26;
        if (loop > 0) {
            colCode += genLexicalKey(loop - 1);
        }
        key = (char) (key + index % 26);
        colCode += key;
        return colCode;
    }

    public static String genAutoIncreaseName(List<String> existsName, String candidate){
        return genAutoIncreaseName(existsName, candidate, 0);
    }

    public static String genAutoIncreaseName(List<String> existsName, String candidate, Integer index){
        String result = "";
        if (index != 0) {
            result = candidate+ "(" + index + ")";
        } else {
            result = candidate;
        }
        if (existsName.contains(result)) {
            result = genAutoIncreaseName(existsName, candidate, ++index);
        }
        return result;
    }

    public static String generateKey(String... args) {
        return generateKey(Arrays.asList(args));
    }

    public static String generateKey(List<String> args) {
        StringBuilder builder = new StringBuilder();
        for (String arg : args) {
            if (arg.isEmpty()) {
                builder.append('#');
            } else {
                builder.append(arg);
            }
            builder.append("-");
        }

        return builder.toString();
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static String generateHashKey(String... args) {
        return generateHashKey(generateKey(Arrays.asList(args)));
    }

    public static String generateHashKey(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
            mDigest.update(key.getBytes(StandardCharsets.UTF_8));
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    public static boolean isAllNumeric(String str) {
        return StringUtils.isNumeric(str);
    }

    /**
     * 按照oldName的格式拼装 新内容
     *
     * @param newName
     * @param oldName
     * @return
     */
    public static String replaceTableName(String newName, String oldName) {
        if (oldName.split("\\.").length > 1) {
            String[] oldParts = oldName.split("\\.");
            String[] newParts = newName.split("\\.");
            return oldParts[0] + "." + newParts[newParts.length - 1];
        } else {
            String[] newParts = newName.split("\\.");
            return newParts[newParts.length - 1];
        }
    }

    public static String addHtmlBoldLabel(String str) {
        if (StringUtils.isNotBlank(str)) {
            str = "<b>" + str + "</b>";
        }
        return str;
    }

    /**
     * 将中文双引号 替换成英文双引号
     *
     * @param str
     * @return
     */
    public static String removeChineseQuote(String str) {
        Pattern p = Pattern.compile("“(.*?)”");
        Matcher m = p.matcher(str);
        while (m.find()) {
            String group = m.group();
            String newIdentifier = group.substring(1, group.length() - 1).trim();
            str = str.replace(group, "\"" + newIdentifier + "\"");
        }
        return str;
    }

    public static boolean containsAllNumAndSpecial(String fieldName) {
        return fieldName.trim().matches("\\d+_") || fieldName.trim().matches("\\d+");
    }

    public static boolean hasSpecialCharacter(String fieldName) {
        return fieldName.trim().matches(DatasetConstant.SPECIAL_CHARACTER_REGEX);
    }

    public static String replaceAngleBrackets(String str) {
        str = str.replaceAll("<", "&lt;");
        str = str.replaceAll("\"", "&quot;");
        str = str.replaceAll(">", "&gt;");
        return str;
    }

    public static String extractTextFromHtml(String htmlStr) {
        String textStr = "";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;
        java.util.regex.Pattern p_html1;
        java.util.regex.Matcher m_html1;
        try {
            String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script>
            String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style>
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            String regEx_html1 = "<[^>]+";
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签
            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签
            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签
            p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
            m_html1 = p_html1.matcher(htmlStr);
            htmlStr = m_html1.replaceAll(""); // 过滤html标签
            textStr = htmlStr;
        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }
        return textStr;// 返回文本字符串
    }

    public static List<String> extractMsgFromBuckets(String msg){

        List<String> list= Lists.newArrayList();
        Pattern p = Pattern.compile("(?<=\\（|\\()(\\S+)(?=\\）|\\))");
        Matcher m = p.matcher(msg);
        while(m.find()){
            list.add(m.group());
        }
        return list;
    }

    public static void main(String[] args) {

        ArrayList<String> objects = Lists.newArrayList();
        objects.add("AA");
        objects.add("AA(1)");
        System.out.println(genAutoIncreaseName(objects, "AA"));
    }

    public static String convertToString(Object obj){
        if (obj instanceof String){
            return obj.toString();
        }else if (obj instanceof Number){
            return String.valueOf(obj);
        }
        return "";
    }

    public static String replaceAndOrSymbol(String s) {
        return s.replaceAll("&&", " AND ").replaceAll("\\|\\|"," OR ").replaceAll("!=", " IS NOT ");
    }

    public static String readInputStreamToString(InputStream stream, Charset charset) throws IOException {
        char[] buffer = new char[1024];
        StringBuilder out = new StringBuilder();
        InputStreamReader in = new InputStreamReader(stream, charset);

        while(true) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0) {
                return out.toString();
            }

            out.append(buffer, 0, rsz);
        }
    }
}
